import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const userInfoReset = {
	username: '',
	nickname: '未登录用户',
	phone: '',
	gender: '女',
	avatar: '/static/nopic.png',
	liked: 0,
	commented: 0,
  signature: ''
}

const store = new Vuex.Store({
	state: {
		loginState: !!uni.getStorageSync('loginState') ? true : false,
		userInfo: !!uni.getStorageSync('userInfo') ? JSON.parse(uni.getStorageSync('userInfo')) : userInfoReset
	},
	getters: {
		
	},
	//同步
	mutations: {
		userLogin(state, userInfo) {
			state.loginState = true
			state.userInfo = userInfo
			uni.setStorageSync('loginState', 'ok')
			uni.setStorageSync('userInfo', JSON.stringify(userInfo))
		},
		userLogout(state) {
			state.loginState = false
			state.userInfo = userInfoReset
			uni.removeStorageSync('userInfo')
			uni.removeStorageSync('loginState')
			uni.removeStorageSync('token')
		},
    updateInfo(state, userInfo) {
      state.userInfo.nickname = userInfo.nickname
      state.userInfo.avatar = userInfo.avatar
      state.userInfo.gender = userInfo.gender
      state.userInfo.phone = userInfo.phone
      state.userInfo.signature = userInfo.signature
      uni.setStorageSync('userInfo', JSON.stringify(userInfo))
    }
	},
	// 通过提交 mutations 内部的方法，异步更新 state 的状态，官方推荐都使用这种方法比较合适
	actions: {
		doUserLogin(context, userInfo) {
			context.commit('userLogin', userInfo)
		},
		doUserLogout(context) {
			context.commit('userLogout')
		}
	}
})

export default store